<?php

namespace app\admin\controller\api;

use app\common\model;
use app\common\model\Classes;
use app\common\model\CourseDetail;

/**
 * 卡
 * @internal
 */
class Card extends Api
{
    protected $noNeedLogin = ['getByNumber'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 根据卡号获取 学生、教师
     *
     * @param card_number string 卡号
     * @param class_id int 班级id
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getByNumber()
    {
        $card_number = $this->request->request('card_number');
        $class_id = $this->request->request('class_id', 0);

        if (!$card_number) {
            $this->error('参数错误');
        }

        $classes = Classes::get($class_id);
        if (!$classes) {
            $this->error('班级不存在');
        }

        $student = \app\common\model\Student::alias('student')
            ->join('__CLASS_STUDENT__ class_student', 'class_student.student_id = student.id')
            ->where('student.card_number', $card_number)
            ->where('class_student.class_id', $class_id)
            ->field('student.id,student.card_number,student.avatar,student.number,student.name,class_student.class_id')
            ->find();

        if ($student) {
            $student->avatar = config('app_url') . $student->avatar;
            $student->type = 'student';
            $this->success('', $student);
        }

        $teacher = model\Teacher::alias('teacher')
            ->join('__USER__ user', 'user.id = teacher.user_id')
            ->where('teacher.card_number', $card_number)
            ->where('teacher.school_id', $classes->school_id)
            ->field('teacher.id,teacher.card_number,user.nickname name,user.avatar,user.mobile,school_id')
            ->find();

        if ($teacher) {
            $teacher->avatar = config('app_url') . $teacher->avatar;
            $teacher->type = 'teacher';
            $this->success('', $teacher);
        }

        $this->error('数据不存在');

    }
}